package com.budong.service.proxy;

import com.budong.utils.TimeUtils;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.UUID;

import static com.budong.common.GifConstant.*;

/**
 * Created by jianweilin on 2017/1/14.
 */
@Service
public class GifProxyService {

    @Value("${unite.gif.shell.path}")
    private String shellPath;

    @Value("${remove.gif.shell.path}")
    private String removeShellPath;

    @Value("${compress.gif.shell.path}")
    private String compressShellPath;

    @Value("${base.path}")
    private String basePath;


    @Value("${gif.size.high}")
    private String gifSizeHigh;

    @Value("${gif.size.middle}")
    private String gifSizeMiddle;

    @Value("${gif.size.low}")
    private String gifSizeLow;

    @Value("${gif.compress.ratio}")
    private String compressRatio;

    public Boolean isYouTUAndAcFunc(String videoUrl) {
        return videoUrl.contains(YOU_KU) || videoUrl.contains(TU_DOU) || videoUrl.contains(AC_FUN);
    }

    public List<String> getRealVideoUrl(String url, String type) {
        String command = "";
        List<String> realUrls = Lists.newArrayList();

        switch (type) {
            case YOU_KU:
            case TU_DOU:
            case AC_FUN:
                command = new StringBuilder("/root/software/you-get -F mp4 -u ").append(url.trim()).toString();
                break;
            case TECENT:
            case BAO_MI_HUA:
            case FUN_TV:
            case YIN_YUE_TAI:
                command = new StringBuilder("/root/software/you-get -u ").append(url.trim()).toString();
                break;
            default:
                throw new IllegalArgumentException("不存在该视频类型: type => " + type);
        }
        System.out.println("command => " + command);

        Runtime run = Runtime.getRuntime();

        try {
            Process p = run.exec(command);// 启动另一个进程来执行命令
            p.waitFor();
            BufferedInputStream in = new BufferedInputStream(p.getInputStream());
            BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
            String lineStr;
            while ((lineStr = inBr.readLine()) != null) {
                if (lineStr.trim().startsWith("http")) {
                    realUrls.add(lineStr.trim());
                }
            }
            System.out.println("realUrl size => " + realUrls.size());
            inBr.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return realUrls;
    }

    public String getLocalGifPath(String mp4Url, String startTime, String endTime, String gifSize) {
        String gifPath = new StringBuilder(basePath).append(UUID.randomUUID()).append(".gif").toString();
//        String gifSize;
//
//        if (quality == 1) {
//            gifSize = gifSizeHigh;
//        } else if (quality == 2) {
//            gifSize = gifSizeMiddle;
//        } else {
//            gifSize = gifSizeLow;
//        }

        String makeGifCmd = new StringBuilder("ffmpeg -ss ")
                .append(startTime.trim())
                .append(" -t ")
                .append(TimeUtils.timePeriod(startTime, endTime))
                .append(" -i ")
                .append(mp4Url.trim())
                .append(" -pix_fmt rgb24 -r 10 -s " + gifSize + " ")
                .append(gifPath)
                .toString();
        System.out.println("makeGifCmd => " + makeGifCmd);

        try {
            Process p = Runtime.getRuntime().exec(makeGifCmd);// 启动另一个进程来执行命令
            BufferedInputStream in = new BufferedInputStream(p.getInputStream());
            BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
            String lineStr;
            while ((lineStr = inBr.readLine()) != null) {
                System.out.println(lineStr);
            }
            inBr.close();
            in.close();

            //检查命令是否执行失败。
            if (p.waitFor() != 0) {
                //p.exitValue()==0表示正常结束，1：非正常结束
                return p.exitValue() == 1 ? GIF_MAKE_ERROR : gifPath;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return gifPath;
    }


    public String getLocalUnitGif(String gifA, String gifB) {
        try {
            String localGifA = _getLocalGifPath(gifA);
            System.out.println("localGifA => " + localGifA);

            String localGifB = _getLocalGifPath(gifB);
            System.out.println("localGifB => " + localGifB);

            if (UNITE_GIF_ERROR.equals(localGifA) || UNITE_GIF_ERROR.equals(localGifB)) {
                return UNITE_GIF_ERROR;
            }

            String unitGif = basePath + UUID.randomUUID() + ".gif";
            System.out.println("unitGif => " + unitGif);

            String makeGifCmd = new StringBuilder(shellPath)
                    .append(localGifA + " ")
                    .append(localGifB + " ")
                    .append(unitGif + " ")
                    .toString();

            System.out.println(" makeGifCmd => " + makeGifCmd);
            Process ps = Runtime.getRuntime().exec(makeGifCmd);
            ps.waitFor();

            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;

            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            String result = sb.toString();
            System.out.println("result => " + result);
            br.close();

            return unitGif;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return UNITE_GIF_ERROR;
    }

    public String _getLocalGifPath(String gif) {
        String[] gifArray = gif.split("/");
        return gifArray.length == 0 ? UNITE_GIF_ERROR : basePath.concat(gifArray[gifArray.length - 1].trim());
    }


    public Integer deleteLocalGif(List<String> gifPaths) {
        long start = System.currentTimeMillis();
        if (gifPaths.size() == 0) {
            return 0;
        }

        StringBuilder deleteGifCmd = new StringBuilder("rm -rf ");
        for (String gif : gifPaths) {
            deleteGifCmd.append(gif + " ");
        }

        System.out.println("makeGifCmd => " + deleteGifCmd);

        try {
            Process p = Runtime.getRuntime().exec(deleteGifCmd.toString());// 启动另一个进程来执行命令
            BufferedInputStream in = new BufferedInputStream(p.getInputStream());
            BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
            String lineStr;
            while ((lineStr = inBr.readLine()) != null) {
                System.out.println(lineStr);
            }
            inBr.close();
            in.close();

            System.out.println("删除本地副本SPEND => " + (System.currentTimeMillis() - start) / 1000 + "秒");
            //检查命令是否执行失败。
            if (p.waitFor() != 0) {
                //p.exitValue()==0表示正常结束，1：非正常结束
                return p.exitValue() == 1 ? 0 : gifPaths.size();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    public void compressLocalGif(String localGif, String compressGif) {
        long start = System.currentTimeMillis();

        String compressGifCmd = new StringBuilder("convert ")
                .append(localGif + " ")
                .append("-fuzz ")
                .append(compressRatio + " ")
                .append("-layers Optimize ")
                .append(compressGif)
                .toString();

        System.out.println("compressGifCmd => " + compressGifCmd);

        try {
            Process p = Runtime.getRuntime().exec(compressGifCmd);// 启动另一个进程来执行命令
            p.waitFor();
            BufferedInputStream in = new BufferedInputStream(p.getInputStream());
            BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
            String lineStr;
            while ((lineStr = inBr.readLine()) != null) {
                System.out.println(lineStr);
            }
            inBr.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("compress Gif SPEND => " + (System.currentTimeMillis() - start) / 1000 + "秒");
    }

    public void compressGifTo500Width(String localGif,String compressGif){
        long start = System.currentTimeMillis();
        try {

            String compressGifTo500WidthCmd = new StringBuilder(compressShellPath + " ")
                    .append(localGif + " ")
                    .append(compressGif + " ")
                    .toString();

            System.out.println(" compressGifTo500WidthCmd => " + compressGifTo500WidthCmd);
            Process ps = Runtime.getRuntime().exec(compressGifTo500WidthCmd);
            ps.waitFor();

            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;

            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("compressGifTo500Width => " + (System.currentTimeMillis() - start) / 1000 + "秒");
    }

    public void removeAllGif(){
        try {
            String removeCmd = new StringBuilder(removeShellPath).toString();

            System.out.println(" removeCmd => " + removeCmd);
            Process ps = Runtime.getRuntime().exec(removeCmd);
            ps.waitFor();

            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;

            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            String result = sb.toString();
            System.out.println("result => " + result);
            br.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
